//
//  OAuthViewController.swift
//  MyWeibo
//
//  Created by cat on 15/7/31.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit
import SVProgressHUD


class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    private lazy var webView = UIWebView()
    // MARK: - 搭建界面
    override func loadView() {
        view = webView
        webView.delegate = self
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
/// 关闭界面
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthUrl()))
    }
    
    // MARK: - UIWebViewDelegate
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        // 判断是否包含回调地址
        if !urlString.hasPrefix(NetworkTools.sharedTools.redirectUrl) {
            return true
        }

        if let query = request.URL?.query where query.hasPrefix("code=") {
        // 从query中截取授权码
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            print("获取授权码" + code)
            // 换取 TOKEN
           loadAccessToken(code)
        
        } else {
            close()
        }
        
        return false
    }
    
    private func loadAccessToken(code: String) {
        NetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                self.netError()
                return
            }
            // 字典转模型
            UserAccount(dict: result!).loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError()
                    return
                }
                
                // 发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(XBXRootViewControllerSwitchNotification, object: false)
                self.close()
            })
        }
    }
    
    deinit {
        print("88")
    }
    
/// 网络出错处理
    private func netError() {
        
        SVProgressHUD.showInfoWithStatus("网络不给力")
        
        let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
        dispatch_after(when, dispatch_get_main_queue()) { () -> Void in
            self.close()
        }
    
    }
    
}
